<template>
  <div class="finance-management">
    <el-card class="box-card">
      <!-- 搜索条件区域 -->
      <el-form 
        :inline="true" 
        :model="searchForm" 
        class="search-form"
        size="mini"
      >
        <el-form-item label="用户ID">
          <el-input 
            v-model="searchForm.id" 
            placeholder="请输入ID" 
            clearable
            style="width: 120px"
          ></el-input>
        </el-form-item>

        <el-form-item label="财务昵称">
          <el-input 
            v-model="searchForm.nickname" 
            placeholder="请输入昵称" 
            clearable
            style="width: 160px"
          ></el-input>
        </el-form-item>

        <el-form-item label="性别">
          <el-select 
            v-model="searchForm.financeSex" 
            placeholder="请选择" 
            clearable
            style="width: 120px"
          >
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="地址">
          <el-select 
            v-model="searchForm.addressName" 
            placeholder="请选择" 
            clearable
            style="width: 160px"
          >
            <el-option 
              v-for="item in addressList" 
              :key="item.id" 
              :label="item.addressName" 
              :value="item.addressName"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item class="search-btns">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="success" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>

      <!-- 财务用户列表表格 -->
      <el-table 
        :data="financeList" 
        style="width: 100%" 
        v-loading="loading"
        border
        stripe
        size="mini"
      >
        <el-table-column prop="id" label="财务ID" width="80" align="center"></el-table-column>
        <el-table-column prop="financeNickname" label="财务昵称" align="center"></el-table-column>
        <el-table-column prop="financeName" label="真实姓名" align="center"></el-table-column>
        <el-table-column prop="financeSex" label="性别" align="center"></el-table-column>
        <el-table-column prop="financeEmail" label="邮箱" align="center"></el-table-column>
        <el-table-column prop="addressName" label="地址" align="center"></el-table-column>
        <el-table-column prop="userTelephone" label="联系电话" align="center"></el-table-column>
        <el-table-column prop="userStatus" label="状态" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.userStatus === 0 ? 'success' : 'danger'" size="mini">
              {{ scope.row.userStatus === 0 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" align="center"></el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button 
              size="mini" 
              type="text" 
              @click="handleEdit(scope.row)"
              icon="el-icon-edit"
            >
              编辑
            </el-button>
            <el-button 
              size="mini" 
              type="text" 
              @click="handleDelete(scope.row)"
              icon="el-icon-delete"
              class="delete-btn"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="pagination"
        size="mini"
      ></el-pagination>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog 
      :title="dialogTitle" 
      :visible.sync="dialogVisible" 
      width="50%"
      center
      size="mini"
    >
      <el-form 
        :model="formData" 
        label-width="120px" 
        ref="formRef"
        :rules="formRules"
        size="mini"
      >
        <el-form-item label="财务ID" v-if="formData.id">
          <el-input v-model="formData.id" disabled></el-input>
        </el-form-item>
        
        <!-- 用户ID不可修改，始终显示且禁用 -->
        <el-form-item label="用户ID" prop="userId">
          <el-input 
            v-model="formData.userId" 
            placeholder="请输入关联用户ID" 
            :disabled="!!formData.id"  
          ></el-input>
        </el-form-item>
        
        <el-form-item label="真实姓名" prop="financeName">
          <el-input v-model="formData.financeName" placeholder="请输入真实姓名"></el-input>
        </el-form-item>
        
        <el-form-item label="财务昵称" prop="financeNickname">
          <el-input v-model="formData.financeNickname" placeholder="请输入财务昵称"></el-input>
        </el-form-item>
        
        <el-form-item label="性别" prop="financeSex">
          <el-select v-model="formData.financeSex" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="邮箱" prop="financeEmail">
          <el-input v-model="formData.financeEmail" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        
        <!-- 地址自动回显 -->
        <el-form-item label="地址" prop="addressId">
          <el-select v-model="formData.addressId" placeholder="请选择地址">
            <el-option 
              v-for="item in addressList" 
              :key="item.id" 
              :label="item.addressName" 
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="saveForm" size="mini">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import adminApi from '@/http/adminApi.js';

export default {
  name: 'FinanceManagement',
  data() {
    return {
      addressList: [],
      searchForm: {
        id: '',
        nickname: '',
        financeSex: '',
        addressName: '',
        tenantId: 1 // 假设租户ID固定为1
      },
      financeList: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: '',
      formData: {
        id: null,
        userId: '',
        financeAvatar: '',
        financeSex: '男',
        financeName: '',
        financeNickname: '',
        financeEmail: '',
        addressId: null,
        tenantId: 1
      },
      formRules: {
        userId: [
          { required: true, message: '请输入用户ID', trigger: 'blur' }
        ],
        financeName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' }
        ],
        financeNickname: [
          { required: true, message: '请输入财务昵称', trigger: 'blur' }
        ],
        financeSex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        financeEmail: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
        ],
        addressId: [
          { required: true, message: '请选择地址', trigger: 'change' }
        ]
      }
    };
  },
  mounted() {
    this.initData();
  },
  methods: {
    async initData() {
      try {
        await this.fetchAddressList();
        await this.fetchFinanceList();
      } catch (error) {
        this.$message.error('页面初始化失败');
      }
    },

    async fetchAddressList() {
      try {
        const res = await adminApi.getAddressList();
        if (res.code === 200) {
          this.addressList = res.data || [];
        }
      } catch (error) {
        this.$message.error('获取地址列表失败');
      }
    },

    async fetchFinanceList() {
      this.loading = true;
      try {
        // 搜索时性别参数转换：汉字→数字
        const sexMap = { '男': 0, '女': 1 };
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize,
          ...this.searchForm,
          financeSex: this.searchForm.financeSex ? sexMap[this.searchForm.financeSex] : null
        };
        const res = await adminApi.getFinances(params);
        if (res.code === 200) {
          // 列表回显时数字→汉字
          this.financeList = (res.data.list || []).map(item => ({
            ...item,
            financeSex: item.financeSex === 0 ? '男' : '女'
          }));
          this.total = res.data.total || 0;
        } else {
          this.$message.error(res.message || '获取财务列表失败');
        }
      } catch (error) {
        this.$message.error('获取财务列表异常');
      } finally {
        this.loading = false;
      }
    },

    handleSearch() {
      this.currentPage = 1;
      this.fetchFinanceList();
    },

    resetSearch() {
      this.searchForm = {
        id: '',
        nickname: '',
        financeSex: '',
        addressName: '',
        tenantId: 1
      };
      this.handleSearch();
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchFinanceList();
    },

    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchFinanceList();
    },

    handleAdd() {
      this.dialogTitle = '新增财务用户';
      this.formData = {
        id: null,
        userId: '',
        financeAvatar: '',
        financeSex: '男',
        financeName: '',
        financeNickname: '',
        financeEmail: '',
        addressId: null,
        tenantId: 1
      };
      this.dialogVisible = true;
    },

    async handleEdit(row) {
      this.dialogTitle = '编辑财务用户';
      this.loading = true;
      try {
        const res = await adminApi.getFinanceDetail({ id: row.id });
        if (res.code === 200 && res.data) {
          // 编辑回显时数字→汉字，地址通过addressId自动匹配
          this.formData = {
            ...res.data,
            financeSex: res.data.financeSex === 0 ? '男' : '女',
            tenantId: 1
          };
          this.dialogVisible = true;
        }
      } catch (error) {
        this.$message.error('获取详情失败');
      } finally {
        this.loading = false;
      }
    },

    async saveForm() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        // 提交时汉字→数字
        const submitData = {
          ...this.formData,
          financeSex: this.formData.financeSex === '男' ? 0 : 1
        };

        this.loading = true;
        try {
          let res;
          if (this.formData.id) {
            res = await adminApi.updateFinance(submitData);
          } else {
            res = await adminApi.addFinance(submitData);
          }
          
          if (res.code === 200) {
            this.$message.success(this.formData.id ? '修改成功' : '新增成功');
            this.dialogVisible = false;
            this.fetchFinanceList();
          } else {
            this.$message.error(res.message || '操作失败');
          }
        } catch (error) {
          this.$message.error('操作异常');
        } finally {
          this.loading = false;
        }
      });
    },

    async handleDelete(row) {
      try {
        await this.$confirm('确定要删除该财务用户吗？', '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        this.loading = true;
        const res = await adminApi.deleteFinance({ id: row.id });
        if (res.code === 200) {
          this.$message.success('删除成功');
          this.fetchFinanceList();
        } else {
          this.$message.error(res.message || '删除失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除异常');
        }
      } finally {
        this.loading = false;
      }
    }
  }
};
</script>

<style scoped>
.search-form {
  margin: 10px 0 20px;
  padding: 10px 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
.delete-btn {
  color: #f56c6c;
}
</style>